<!--
 * @Description: 
 * @Version: 2.0
 * @Autor: jerry.zzy
 * @Date: 2020-11-03 09:36:52
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2022-02-10 10:51:53
-->
//↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘注释↙↙↙↙↙↙↙↙↙↙↙↙↙↙↙↙ 
（1）添加和修改中的
创建人是当前登陆人不能改
（2）搜索表单中增加“是否必检”，下拉框显示是、否，是字典表
（3）表单中增加“是否必检”，相应添加、修改弹窗总也加上是否必检
（4）表格中增加一个所属仓库，调用库存组织档案的列表（多选），是为了将存货编码和仓库联系起来
(5) :filter-option="filterOption" 前端模糊查询
//↗↗↗↗↗↗↗↗↗↗↗↗↗↗↗↗↗↗↗↗↖↖↖↖↖↖↖↖↖↖↖↖↖↖↖↖↖↖
//↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘注释↙↙↙↙↙↙↙↙↙↙↙↙↙↙↙↙ 1 新增、修改 的
存货分类把父节点全部设置成禁选 2 搜索框 选择存货分类 自动出对应的存货编码
//↗↗↗↗↗↗↗↗↗↗↗↗↗↗↗↗↗↗↗↗↖↖↖↖↖↖↖↖↖↖↖↖↖↖↖↖↖↖
<template>
  <a-card>
    <div v-show="showSpin">
      <a-spin tip="等待导出..." size="large">
        <div class="spin-content"></div>
      </a-spin>
    </div>
    <a-form-model :model="formdata" v-bind="layout" :rules="rules">
      <a-row>
        <!-- 搜索栏 -->

        <!-- <a-col :lg="6" :md="6" :sm="24">
          <a-form-model-item label="存货分类">
            <a-tree-select
              showSearch
              v-model="formdata.sort"
              style="width: 100%"
              allow-clear
              :tree-data="inventoryNoList"
              @change="sortchange"
              onSelect
              tree-node-filter-prop="title"
           
            >
            </a-tree-select>

          
          </a-form-model-item>
        </a-col> -->
        <a-col :lg="6" :md="6" :sm="24">
          <a-form-model-item label="存货编码">
            <a-select
              v-model="formdata.inventoryNo"
              @search="handleSearchByNo"
              style="width: 100%"
              showSearch
              @change="
                (val) => {
                  const arr = val.split('|');
                  this.formdata.inventoryId = arr[0];
                  this.formdata.inventoryNo = arr[1];
                  this.formdata.inventoryName = arr[2];
                }
              "
            >
              <a-select-option
                v-for="(item, index) in goodsList"
                :key="index"
                :value="
                  item.inventoryId +
                  '|' +
                  item.inventoryNo +
                  '|' +
                  item.inventoryName +
                  '|' +
                  item.specificationsModel +
                  '|' +
                  item.unit
                "
              >
                {{ item.inventoryNo }} {{ item.inventoryName }}
                {{ item.specificationsModel }}</a-select-option
              >
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :lg="12" :md="12" :sm="24">
          <a-form-model-item label="存货名称">
            <a-input v-model="formdata.inventoryName"> </a-input>
            <!--   <a-select
              v-model="formdata.inventoryName"
              @search="handleSearch"
              @change="
                (val) => {
                  const arr = val.split('|');
                  this.formdata.inventoryId = arr[0];
                  this.formdata.inventoryNo = arr[1];
                  this.formdata.inventoryName = arr[2];
                }
              "
              showSearch
            >
              <a-select-option
                v-for="(item, index) in goodsList"
                :key="index"
                :value="
                  item.inventoryId +
                  '|' +
                  item.inventoryNo +
                  '|' +
                  item.inventoryName +
                  '|' +
                  item.specificationsModel
                "
                >{{ item.inventoryNo }} {{ item.inventoryName
                }}{{ item.specificationsModel }}</a-select-option
              >
            </a-select> -->
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :lg="6" :md="6" :sm="24" align="right" style="float: right">
          <a-button type="primary" @click="getsearch"> 查询 </a-button>
          <a-button :style="{ marginLeft: '8px' }" @click="handleReset">
            重置
          </a-button>
          <a-button
            :loading="asyncLoad"
            type="primary"
            :style="{ marginLeft: '8px' }"
            @click="SyncData"
          >
            与用友同步
          </a-button>
        </a-col>
        <a-col :lg="18" :md="18" :sm="24"> </a-col>

        <!-- <a-button
          type="primary"
          @click="showModalXinZeng"
          style="margin-bottom: 10px"
        >
          <a-icon type="plus" />
          添加存货信息
        </a-button> -->

        <a-button
          type="primary"
          style="float: left; margin-bottom: 10px"
          @click="exportExcel"
        >
          导出</a-button
        >

        <!-- 彈窗开始 -->
        <a-modal
          :visible="visibleXinZeng"
          width="50%"
          title="添加存货信息"
          okText="确定"
          @cancel="handleCancel2"
          @ok="handleOk2"
        >
          <a-form-model
            ref="ruleForm"
            :rules="rules"
            :model="xinzeng_formdata"
            v-bind="layout"
          >
            <a-row>
              <a-col :md="10" :sm="24">
                <a-form-model-item
                  ref="inventoryNo"
                  label="存货编码"
                  prop="inventoryNo"
                >
                  <a-input v-model="xinzeng_formdata.inventoryNo" disabled />
                </a-form-model-item>
              </a-col>

              <a-col :md="10" :sm="24">
                <a-form-model-item
                  ref="inventoryName"
                  label="存货名称"
                  prop="inventoryName"
                >
                  <a-input v-model="xinzeng_formdata.inventoryName" />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row>
              <a-col :md="10" :sm="24">
                <a-form-model-item
                  ref="specificationsModel"
                  label="型号规格"
                  prop="specificationsModel"
                >
                  <a-input v-model="xinzeng_formdata.specificationsModel" />
                </a-form-model-item>
              </a-col>
              <a-col :md="10" :sm="24">
                <a-form-model-item ref="unit" label="单位" prop="unit">
                  <!-- <a-input v-model="xinzeng_formdata.unit" /> -->

                  <a-select v-model="xinzeng_formdata.unit">
                    <a-select-option
                      v-for="item in unitList"
                      :key="item.value"
                      :value="item.title"
                    >
                      {{ item.title }}</a-select-option
                    >
                  </a-select>
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row>
              <a-col :md="10" :sm="24">
                <a-form-model-item ref="userId" label="创建人" prop="userId">
                  <a-input v-model="xinzeng_formdata.userId" disabled />
                </a-form-model-item>
              </a-col>
              <a-col :md="10" :sm="24">
                <a-form-model-item
                  ref="createTime"
                  label="创建时间"
                  prop="createTime"
                >
                  <a-date-picker
                    v-model="xinzeng_formdata.createTime"
                    type="date"
                    style="width: 100%"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :md="10" :sm="24">
                <a-form-model-item ref="sort" label="存货分类" prop="sort">
                  <a-tree-select
                    showSearch
                    v-model="xinzeng_formdata.sort"
                    style="width: 100%"
                    allow-clear
                    :tree-data="inventoryNoList"
                    @change="sortchange_createInventoryNo"
                    onSelect
                    tree-node-filter-prop="title"
                  >
                  </a-tree-select>

                  <!-- <a-select placeholder="" v-model="xinzeng_formdata.sort">
                    <a-select-option
                      v-for="val in inventoryNoList"
                      :key="val.value"
                      :value="val.value"
                      >{{ val.title }}</a-select-option
                    >
                  </a-select> -->
                </a-form-model-item>
              </a-col>

              <a-col :md="10" :sm="24">
                <a-form-model-item label="是否必检" ref="necessaryToCheck">
                  <a-select v-model="xinzeng_formdata.necessaryToCheck">
                    <a-select-option value="1"> 是 </a-select-option>
                    <a-select-option value="2"> 否 </a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>

              <a-col :md="10" :sm="24">
                <a-form-model-item
                  ref="inventoryInformationOrganizationId"
                  label="所属仓库"
                  prop="inventoryInformationOrganizationId"
                >
                  <a-select
                    v-model="
                      xinzeng_formdata.inventoryInformationOrganizationId
                    "
                    mode="multiple"
                    @change="ChangeWarehouse"
                    :filter-option="filterOption"
                  >
                    <a-select-option
                      v-for="item in WarehouseCodeList"
                      :key="item.id"
                      :value="item.id"
                    >
                      {{ item.depotName }}</a-select-option
                    >
                  </a-select>
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-form-model>
        </a-modal>
        <!-- 新增弹窗结束 -->
      </a-row>
    </a-form-model>

    <!-- 表格 -->

    <a-table
      size="middle"
      bordered
      :data-source="dataSource"
      :columns="columns"
      :pagination="pagination"
      @change="handleTableChange"
      id="myTable"
      :rowKey="(record) => record.pkInvbasdoc"
    >
      <template slot="序号" slot-scope="text, record">
        <editable-cell
          :text="text"
          @change="onCellChange(record.key, 'xuhao', $event)"
        />
      </template>
      <template slot="caozuo" slot-scope="text, record">
        <!-- 修改按钮与修改页面 -->

        <a type="primary" @click="showModal1(record)"> 修改 </a>

        <!-- <a-divider type="vertical" /> -->
        <!-- 删除提示 -->
        <!-- <a-popconfirm
          v-if="dataSource.length"
          title="是否确认删除?"
          @confirm="onDelete(record.id)"
        >
          <a href="javascript:;">删除</a>
        </a-popconfirm> -->
      </template>
    </a-table>
    <!-- 修改弹窗开始 -->
    <a-modal
      title="修改"
      :visible="visible1"
      width="50%"
      @ok="handleOk1"
      @cancel="handleCancel1"
      cancelText="取消"
      okText="保存"
    >
      <a-form-model
        ref="ruleForm"
        :model="xiugai_formdata"
        :rules="rules"
        v-bind="layout"
      >
        <a-row>
          <a-col :md="10" :sm="24">
            <a-form-model-item
              ref="inventoryNo"
              label="存货编码"
              prop="inventoryNo"
            >
              <a-input v-model="xiugai_formdata.inventoryNo" disabled />
            </a-form-model-item>
          </a-col>

          <a-col :md="10" :sm="24">
            <a-form-model-item
              ref="inventoryName"
              label="存货名称"
              prop="inventoryName"
            >
              <a-input v-model="xiugai_formdata.inventoryName" />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :md="10" :sm="24">
            <a-form-model-item
              ref="specificationsModel"
              label="规格型号"
              prop="specificationsModel"
            >
              <a-input v-model="xiugai_formdata.specificationsModel" />
            </a-form-model-item>
          </a-col>

          <a-col :md="10" :sm="24">
            <a-form-model-item ref="unit" label="单位" prop="unit">
              <a-select v-model="xiugai_formdata.unit">
                <a-select-option
                  v-for="item in unitList"
                  :key="item.value"
                  :value="item.title"
                >
                  {{ item.title }}</a-select-option
                >
              </a-select>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :md="10" :sm="24">
            <a-form-model-item ref="userId" label="创建人" prop="userId">
              <a-input v-model="xiugai_formdata.userId" disabled />
            </a-form-model-item>
          </a-col>
          <a-col :md="10" :sm="24">
            <a-form-model-item
              ref="createTime"
              label="创建时间"
              prop="createTime"
            >
              <a-date-picker
                v-model="xiugai_formdata.createTime"
                type="date"
                style="width: 100%"
              />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :md="10" :sm="24">
            <a-form-model-item ref="sort" label="存货分类" prop="sort">
              <!-- <a-select placeholder="" v-model="xiugai_formdata.sort">
                <a-select-option
                  v-for="val in inventoryNoList"
                  :key="val.value"
                  :value="val.value"
                  >{{ val.title }}</a-select-option
                >
              </a-select> -->

              <a-tree-select
                showSearch
                v-model="xiugai_formdata.sort"
                style="width: 100%"
                allow-clear
                :tree-data="inventoryNoList"
                @change="sortchange"
                onSelect
                tree-node-filter-prop="title"
              >
              </a-tree-select>
            </a-form-model-item>
          </a-col>

          <a-col :md="10" :sm="24">
            <a-form-model-item
              label="是否必检"
              ref="necessaryToCheck"
              prop="necessaryToCheck"
            >
              <a-select v-model="xiugai_formdata.necessaryToCheck">
                <a-select-option value="1"> 是 </a-select-option>
                <a-select-option value="2"> 否 </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :md="10" :sm="24">
            <a-form-model-item
              ref="inventoryOrganizationId"
              label="所属仓库"
              prop="inventoryOrganizationId"
            >
              <a-select
                v-model="xiugai_formdata.inventoryOrganizationId"
                mode="multiple"
                @change="ChangeWarehouse_update"
                :filter-option="filterOption"
              >
                <a-select-option
                  v-for="item in WarehouseCodeList"
                  :key="item.id"
                  :value="item.id"
                >
                  {{ item.depotName }}</a-select-option
                >
              </a-select>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </a-modal>
    <!-- 修改弹窗结束 -->
  </a-card>
</template>

<script>
import FileSaver from "file-saver";
import XLSX from "xlsx";
// import { ZiDianBiaoHttp } from "../../services/modules/ZiDianBiao";
// const $ZDB = new ZiDianBiaoHttp();

import { CommonAjax } from "../../services/modules/common";
const common = new CommonAjax();
import { CunHuoXinXiHttp } from "../../services/modules/JiChuXinXiGuanLi/CunHuoXinXiDangAn";
const $http = new CunHuoXinXiHttp();
import moment from "moment";
import "moment/locale/zh-cn";
import { sheet2blob } from "@/utils/export.js";
// import { JiChuXinXiSheZhiHttp } from "../../services/modules/JiChuXinXiSheZhi";
// const $http = new JiChuXinXiSheZhiHttp();
import axios from "axios";
const cangkuname = [
  {
    key: 1,
    id: 1,
    name: "山东七河生物",
  },
  {
    key: 2,
    id: 2,
    name: "双泉原料库",
  },
  {
    key: 3,
    id: 3,
    name: "双泉辅料库",
  },
];

export default {
  data() {
    return {
      // replaceFields: {
      //   children: "syncInventoryClassificationEntityList",
      //   title: "invclassname",
      // },
      sort_U8C: "", //往u8c里传的id,
      depotNo_jiaoyan: "",
      inventoryInformationOrganizationList: [],
      saveBatch: [], //存货分类与仓库关系-保存存货分类和仓库关系
      saveBatch_huixian: [], //新增时选择存货分类，获取所属仓库存放在这里
      unitList: [],
      array: [],
      array_xiugai: [],
      ChooseWarehouse: "",
      WarehouseCodeList: [], //所有的仓库编码、仓库名称、id
      showSpin: false, //打印加载中
      queryParam: {
        //查询参数
        page: 1, //第几页
        size: 10, //每页中显示数据的条数
        hosName: "",
        hosCode: "",
        province: "",
        city: "",
      },
      //===============分页========================
      pagination: {
        total: 0,
        current: 1,
        pageSize: 10, //每页中显示10条数据
        pageSizeOptions: ["10"], //每页中显示的数据
        showTotal: (total) => `共有${total}条数据`, //分页中显示总的数据
        showQuickJumper: true, // 显示快速跳转
      },
      asyncLoad: false,
      //新增弹窗
      visibleXinZeng: false,
      xinzeng_formdata: {
        sysUserId: "", //创建人的userid
        inventoryNo: "",
        inventoryName: "",
        unit: "",
        userId: "",
        createTime: null,
        sort: "",
        necessaryToCheck: "", //是否必检
        inventoryInformationOrganizationId: undefined, //所属仓库
      },
      visible1: false, //修改弹窗
      xiugai_formdata: {
        inventoryNo: "",
        inventoryName: "",
        unit: "",
        userId: "",
        createTime: null,
        sort: "",
        necessaryToCheck: "", //是否必检
        inventoryOrganizationId: undefined, //所属仓库
        id: "",
      },

      formdata: {
        //增加数据
        necessaryToCheck: "", //是否必检
        sort: "",
        inventoryNo: "",
        inventoryName: "",
      },
      cangkuname,
      inventoryNoList: [], //存货分类
      danweiList: [], //danwei
      goodsList: [], //获取存货编码、名称
      // 增加栏的格式
      layout: {
        labelCol: { span: 8 },
        wrapperCol: { span: 15 },
      },

      // 导出专用
      maxSize: "",

      // 表格数据
      dataSource: [],
      count: 2,
      columns: [
        {
          key: "xuhao",
          title: "序号",
          dataIndex: "xuhao",
          align: "center",
          scopedSlots: { customRender: "xuhao" },
        },
        // {
        //   key: "pkInvcl",
        //   title: "分类",
        //   dataIndex: "pkInvcl",
        //   align: "center",
        // },
        {
          key: "invcode",
          title: "存货编码",
          dataIndex: "invcode",
          align: "center",
        },
        {
          key: "invname",
          title: "存货名称",
          dataIndex: "invname",
          align: "center",
        },

        {
          key: "invtype",
          title: "型号",
          dataIndex: "invtype",
          align: "center",
        },
        {
          key: "invspec",
          title: "规格",
          dataIndex: "invspec",
          align: "center",
        },
        {
          key: "pkMeasdoc_dictText",
          title: "主计量单位",
          dataIndex: "pkMeasdoc_dictText",
          align: "center",
        },

        {
          key: "creator",
          title: "创建人",
          dataIndex: "creator",
          align: "center",
        },
        {
          key: "pkTaxitems",
          title: "税目税率",
          dataIndex: "pkTaxitems",
          align: "center",
        },

        {
          key: "fixedflag",
          title: "是否固定换算",
          dataIndex: "fixedflag",
          align: "center",
        },
        {
          key: "mainmeasrate",
          title: "主计量单位换算系数",
          dataIndex: "mainmeasrate",
          align: "center",
        },
        {
          key: "pkConvert",
          title: "辅计量",
          dataIndex: "pkConvert",
          align: "center",
        },
        {
          key: "sealflag",
          title: "封存标志",
          dataIndex: "sealflag",
          align: "center",
        },
        {
          key: "dr",
          title: "是否删除",
          dataIndex: "dr",
          align: "center",
        },
        {
          key: "laborflag",
          title: "是否应税劳务",
          dataIndex: "laborflag",
          align: "center",
        },
        {
          key: "negallowed",
          title: "是否允许负库存",
          dataIndex: "negallowed",
          align: "center",
        },

        // {
        //   title: "操作",
        //   dataIndex: "caozuo",
        //   scopedSlots: { customRender: "caozuo" },
        //   align: "center",
        // },
      ],
      // 新增验证规则
      rules: {
        inventoryNo: [
          { required: true, message: "存货编码为必填项！", trigger: "blur" },
        ],
        inventoryName: [
          { required: true, message: "存货名称为必填项！", trigger: "blur" },
        ],
        specificationsModel: [
          { required: true, message: "型号规格为必填项！", trigger: "blur" },
        ],
        unit: [{ required: true, message: "单位为必填项！", trigger: "blur" }],
        // userId: [
        //   { required: true, message: "创建人为必填项！", trigger: "blur" },
        // ],
        createTime: [
          { required: true, message: "创建时间为必填项！", trigger: "blur" },
        ],
        // sort: [
        //   { required: true, message: "存货分类为必填项!", trigger: "change" },
        // ],
        // necessaryToCheck: [
        //   { required: true, message: "是否必检为必填项!", trigger: "blur" },
        // ],
        inventoryInformationOrganizationId: [
          { required: true, message: "所属仓库为必填项!", trigger: "blur" },
        ],
        inventoryOrganizationId: [
          { required: true, message: "所属仓库为必填项!", trigger: "blur" },
        ],
      },
    };
  },
  mounted() {
    this.GetInventoryInformationList(); //存货信息档案列表-获取
    this.getInventoryClassificationList(); //获取存货分类
    // this.VariousInventoryInformation(); //存货信息档案-返回存货编码、名称、规格型号、单位
    this.GetUserSectionInfoByToken(); // 根据TOKEN获取用户的部分信息
    this.getAllNumberName(); //返回所有的仓库编码、仓库名称
    this.getAuxiliaryUnit(); //单位字典表
    // this.getgongsi();
  },

  // created() {
  //   Promise.all([this.handleOk2(), this.save_U8C()]).then((res) => {
  //     console.log("res[0]",res[0]);
  //     console.log("res[1]",res[1]);
  //   })
  // },

  methods: {
    //查询实时输入
    handleSearchByNo(value) {
      this.debounce(value, 800);
    },
    //延迟
    debounce(value, wait) {
      if (this.timeout) clearTimeout(this.timeout);
      this.timeout = setTimeout(() => {
        this.onfunc(value);
      }, wait);
    },

    onfunc(value) {
      //模糊查询
      this.goodsList = [];
      console.log("invcode", invcode);
      let invcode = "?invcode=" + value;
      console.log("invcode", invcode);
      if (value == "" || value == null) {
        this.goodsList = [];
      } else {
        common.getqueryInventoryByInvcode(invcode).then((res) => {
          console.log("结果为", res);
          // this.goodsList = res.result;
          for (let i = 0; i < res.result.length; i++) {
            if (
              res.result[i].specificationsModel == "null" ||
              res.result[i].specificationsModel == null
            ) {
              res.result[i].specificationsModel = "";
            }
            if (res.result[i].unit == "null" || res.result[i].unit == null) {
              res.result[i].unit = "";
            }
            let data = {
              inventoryId: res.result[i].pkInvbasdoc, // 存货 id
              inventoryNo: res.result[i].invcode, //存货编码
              inventoryName: res.result[i].invname, //存货名称
              specificationsModel: res.result[i].invspec, //规格型号
              unit: res.result[i].measname, //单位
            };
            this.goodsList.push(data);
          }
        });
      }
    },
    async handleSearch(value) {
      //模糊查询
      var goodsList_invname = [];
      var goodsList_invcode = [];
      if (value.match(/^[ ]*$/)) {
        console.log("字符串为空或全空格");
      } else {
        this.goodsList = [];
        console.log("value", value);
        let query = "?name=" + value;
        console.log("query", query);
        if (value == "" || value == null) {
          this.goodsList = [];
        } else {
          this.goodsList = [];
          // 根据存货名称查询

          await common
            .getgetSearchInventoryInformationFile(query)
            .then((res) => {
              console.log("结果为", res);
              // this.goodsList = res.result;
              for (let i = 0; i < res.result.length; i++) {
                if (
                  res.result[i].specificationsModel == "null" ||
                  res.result[i].specificationsModel == null
                ) {
                  res.result[i].specificationsModel = "";
                }
                if (
                  res.result[i].unit == "null" ||
                  res.result[i].unit == null
                ) {
                  res.result[i].unit = "";
                }
                let data = {
                  inventoryInformationId: res.result[i].pkInvbasdoc, // 存货 id
                  inventoryNo: res.result[i].invcode, //存货编码
                  inventoryName: res.result[i].invname, //存货名称
                  specificationsModel: res.result[i].specificationsModel, //规格型号
                  unit: res.result[i].unit, //单位
                };
                goodsList_invname.push(data);
                // this.goodsList.push(data);
              }
              console.log("这是this.goodsList", this.goodsList);
            });
          // 存货编码模糊查询
          let invcode = "?invcode=" + value;
          console.log("queryInventoryByInvcode", invcode);
          await common.getqueryInventoryByInvcode(invcode).then((res) => {
            console.log("根据存货编码模糊查询", res);
            goodsList_invcode = res.result.map((item) => {
              return {
                inventoryInformationId: item.pkInvbasdoc,
                inventoryNo: item.invcode,
                inventoryName: item.invname,
                specificationsModel: item.invspec,
                unit: item.measname,
              };
            });
          });

          //todo 合并去重函数
          await this.mergeArray(goodsList_invname, goodsList_invcode);
        }
      }
    },
    //todo 合并去重函数
    mergeArray(arr1, arr2) {
      let arrs = [...arr1, ...arr2];

      //根据inventoryId去重
      let map = new Map();
      for (let item of arrs) {
        if (!map.has(item.inventoryInformationId)) {
          map.set(item.inventoryInformationId, item);
        }
      }
      this.goodsList = [...map.values()];
    },
    //搜索开始
    getsearch() {
      let dd = (this.pagination.page = 1); //分页
      (this.dataSource = []), (this.pagination.current = 1);
      if (this.formdata.sort === undefined) {
        this.formdata.sort = "";
      }
      if (this.formdata.inventoryNo === undefined) {
        this.formdata.inventoryNo = "";
      }
      if (this.formdata.inventoryName === undefined) {
        this.formdata.inventoryName = "";
      }
      if (this.formdata.necessaryToCheck === undefined) {
        this.formdata.necessaryToCheck = "";
      }
      $http
        .GetInventoryInformationList(
          "?pageNo=" +
            dd +
            "&invcode=" +
            this.formdata.inventoryNo +
            "&invname=" +
            this.formdata.inventoryName
        )
        .then((res) => {
          const pagination = { ...this.pagination }; //分页
          console.log("this,data", this.data);
          this.data = res.result.records;
          pagination.total = res.result.total; //分页
          pagination.pageSize = res.result.size; //分页
          this.pagination = pagination; //分页
          this.dataSource = res.result.records;
          for (let i = 0; i < res.result.records.length; i++) {
            this.dataSource[i].xuhao = (res.result.current - 1) * 10 + i + 1;
            this.dataSource[i].dr = this.dataSource[i].dr == "0" ? "否" : "是";
            this.dataSource[i].laborflag =
              this.dataSource[i].laborflag == 0 ? "否" : "是";
          }
          console.log("dataSource----->", this.dataSource);
        });
    },
    // /存货信息档案列表-获取
    GetInventoryInformationList() {
      if (this.formdata.sort === undefined) {
        this.formdata.sort = "";
      }
      if (this.formdata.inventoryNo === undefined) {
        this.formdata.inventoryNo = "";
      }
      if (this.formdata.inventoryName === undefined) {
        this.formdata.inventoryName = "";
      }
      if (this.formdata.necessaryToCheck === undefined) {
        this.formdata.necessaryToCheck = "";
      }
      let dd = this.queryParam.page; //分页
      (this.dataSource = []),
        $http.GetInventoryInformationList("?pageNo=" + dd).then((res) => {
          const pagination = { ...this.pagination }; //分页
          this.data = res.result.records;
          pagination.total = res.result.total; //分页
          pagination.pageSize = res.result.size; //分页
          this.pagination = pagination; //分页
          this.maxSize = res.result.total;

          this.dataSource = res.result.records;
          for (let i = 0; i < res.result.records.length; i++) {
            this.dataSource[i].xuhao = (res.result.current - 1) * 10 + i + 1;
            this.dataSource[i].dr = this.dataSource[i].dr == "0" ? "否" : "是";
            this.dataSource[i].laborflag =
              this.dataSource[i].laborflag == 0 ? "否" : "是";
          }
          console.log("dataSource----->", this.dataSource);
        });
    },
    //多选仓库的change函数--数组变数组包对象
    ChangeWarehouse(value) {
      // (this.ChooseWarehouse = `${value}`),
      // console.log(this.ChooseWarehouse, "ChooseWarehouse");
      console.log(value);
      this.inventoryInformationOrganizationList = [];
      for (let i = 0; i < value.length; i++) {
        let data = {
          inventoryOrganizationId: value[i],
        };
        this.inventoryInformationOrganizationList.push(data);
      }
      console.log(
        "this.inventoryInformationOrganizationList",
        this.inventoryInformationOrganizationList
      );
    },

    //多选仓库的change函数
    ChangeWarehouse_update(value) {
      // console.log(this.xiugai_formdata.inventoryOrganizationId);
      console.log(value);
      // this.xiugai_formdata.inventoryOrganizationId = value;
      this.inventoryInformationOrganizationList = [];
      for (let i = 0; i < value.length; i++) {
        let data = {
          id: this.xiugai_formdata.list[0].id,
          inventoryInformationId:
            this.xiugai_formdata.list[0].inventoryInformationId,
          inventoryOrganizationId: value[i],
        };
        this.inventoryInformationOrganizationList.push(data);
      }
      console.log(
        "this.inventoryInformationOrganizationList",
        this.inventoryInformationOrganizationList
      );
    },
    //返回所有的仓库编码、仓库名称
    getAllNumberName() {
      $http.getAllNumberName().then((res) => {
        this.WarehouseCodeList = res.result;
        console.log("返回所有的仓库编码、仓库名称", this.WarehouseCodeList);
      });
    },
    // 根据TOKEN获取用户的部分信息
    GetUserSectionInfoByToken() {
      let querPath = "";
      $http.GetUserSectionInfoByToken(querPath).then((res) => {
        this.xinzeng_formdata.userId = res.result.sysUsername;
        this.xinzeng_formdata.sysUserId = res.result.sysUserId;
      });
    },

    handleCancel1() {
      // 修改弹窗取消
      this.visible1 = false;
    },
    handleReset() {
      this.ResetTab();
      //重置
      this.formdata = {
        sort: "",
        inventoryNo: "",
        inventoryName: "",
        necessaryToCheck: "",
      };
      this.GetInventoryInformationList();
    },
    ResetTab() {
      this.pagination = {
        total: 0,
        current: 1,
        pageSize: 10, //每页中显示10条数据

        showTotal: (total) => `共有${total}条数据`, //分页中显示总的数据
        showSizeChanger: true, // 显示页面条数改变
        showQuickJumper: true, // 显示快速跳转
      };
      //查询参数
      this.queryParam = {
        page: 1, //第几页
        size: 10, //每页中显示数据的条数
        hosName: "",
        hosCode: "",
        province: "",
        city: "",
      };
    },

    //新增弹窗
    showModalXinZeng() {
      this.visibleXinZeng = true;
    },
    handleCancel2() {
      //新增弹窗
      this.visibleXinZeng = !this.visibleXinZeng;
    },
    showModal1(record) {
      this.array_xiugai = []; //重置所属仓库数组
      this.depotNo_jiaoyan = record.inventoryNo;
      (this.array = []), (this.xiugai_formdata = {});

      console.log(record, "record");
      //修改按钮
      this.visible1 = !this.visible1;
      this.xiugai_formdata = record;
      this.xiugai_formdata.necessaryToCheck = record.necessaryToCheck + ""; //是否必检

      //遍历得到所属仓库的数组
      for (let i = 0; i < record.list.length; i++) {
        this.array_xiugai.push(record.list[i].inventoryOrganizationId);
      }
      console.log("this.array_xiugai", this.array_xiugai);
      //走多选仓库change函数,防止不选择仓库直接保存
      this.ChangeWarehouse_update(this.array_xiugai);

      //所属仓库回显
      this.xiugai_formdata.inventoryOrganizationId = this.$set(
        this.xiugai_formdata,
        "inventoryOrganizationId",
        this.array_xiugai
      );

      if (this.xiugai_formdata.necessaryToCheck == "null") {
        this.xiugai_formdata.necessaryToCheck = "";
      }
      console.log("this.xiugai_formdata", this.xiugai_formdata);
    },
    handleOk1() {
      let querPath =
        "?fieldName=" +
        "inventory_no" +
        "&tableName=" +
        "warehouse_inventory_information_file" +
        "&fieldVal=" +
        this.xiugai_formdata.inventoryNo;
      //修改弹窗ok
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          const data = {
            inventoryNo: this.xiugai_formdata.inventoryNo, //存货编码
            inventoryName: this.xiugai_formdata.inventoryName, //存货名称
            specificationsModel: this.xiugai_formdata.specificationsModel, //规格型号
            unit: this.xiugai_formdata.unit, //单位
            // userId: this.xinzeng_formdata.userId, //创建人
            createTime: moment(this.xiugai_formdata.createTime).format(
              "YYYY-MM-DD"
            ), //创建时间
            sort: Number(this.xiugai_formdata.sort), //存货分类
            id: this.xiugai_formdata.id,
            necessaryToCheck: Number(this.xiugai_formdata.necessaryToCheck), //是否必检
            inventoryInformationOrganizationList:
              this.inventoryInformationOrganizationList,
          };
          //如果没有修改存货编码就直接修改，否则 修改了存货编码就走下面的重复检验
          console.log("this.depotNo_jiaoyan", this.depotNo_jiaoyan);
          console.log(
            "this.xiugai_formdata.inventoryNo",
            this.xiugai_formdata.inventoryNo
          );
          if (this.depotNo_jiaoyan == this.xiugai_formdata.inventoryNo) {
            $http.UpdateInventoryInformation(data).then((res) => {
              if (res.success) {
                this.$message.success("保存成功！");
                this.GetInventoryInformationList();
                this.visible1 = false;
                console.log(res);
              } else {
                this.$message.success("保存失败！");
              }
            });
          } else {
            //重复检验
            $http.duplicateCheck(querPath).then((res) => {
              //如果校验成功就发送数据
              if (res.success) {
                $http.UpdateInventoryInformation(data).then((res) => {
                  if (res.success) {
                    this.$message.success("保存成功！");
                    this.GetInventoryInformationList();
                    this.visible1 = false;
                    console.log(res);
                  } else {
                    this.$message.success("保存失败！");
                  }
                });
              } else {
                this.$message.error("存货编码重复！");
              }
            });
          }
        } else {
          console.log("false出现了");
        }
      });
    },
    async handleOk2() {
      let querPath =
        "?fieldName=" +
        "inventory_no" +
        "&tableName=" +
        "warehouse_inventory_information_file" +
        "&fieldVal=" +
        this.xinzeng_formdata.inventoryNo;
      //点击增加按钮
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          const data = {
            inventoryNo: this.xinzeng_formdata.inventoryNo, //存货编码
            inventoryName: this.xinzeng_formdata.inventoryName, //存货名称
            specificationsModel: this.xinzeng_formdata.specificationsModel, //规格型号
            unit: this.xinzeng_formdata.unit, //单位
            userId: this.xinzeng_formdata.sysUserId, //创建人
            createTime: moment(this.xinzeng_formdata.createTime).format(
              "YYYY-MM-DD"
            ), //创建时间
            sort: this.xinzeng_formdata.sort, //存货分类
            necessaryToCheck: this.xinzeng_formdata.necessaryToCheck, //是否必检
            inventoryInformationOrganizationList:
              this.inventoryInformationOrganizationList, //所属仓库
          };
          console.log("data::::::::::", data);

          //重复检验
          $http.duplicateCheck(querPath).then((res) => {
            //如果校验成功就发送数据
            if (res.success) {
              $http.InventoryInformation(data).then((res) => {
                if (res.success) {
                  this.save_U8C(); //保存U8C数据
                  this.$message.success("保存成功！");
                  this.visibleXinZeng = false;
                  this.xinzeng_formdata = {}; //重置
                  this.GetUserSectionInfoByToken(); //重置后重新获取当前登陆人信息
                  this.xinzeng_formdata.createTime =
                    moment().format("YYYY-MM-DD"); //重置后重新获取创建时间
                  this.GetInventoryInformationList();
                  console.log(res);
                } else {
                  this.$message.success("保存失败！");
                }
              });
            } else {
              this.$message.error("存货编码重复！");
            }
          });
        } else {
          console.log("false出现了");
        }
      });
      // 存货分类与仓库关系-保存存货分类和仓库关系
      this.saveBatch = [];

      for (
        let d = 0;
        d < this.inventoryInformationOrganizationList.length;
        d++
      ) {
        let datas = {
          inventoryClassificationId: this.xinzeng_formdata.sort,
          depotId:
            this.inventoryInformationOrganizationList[d]
              .inventoryOrganizationId,
        };
        this.saveBatch.push(datas);
      }
      console.log("this.saveBatch", this.saveBatch);
      $http.saveBatch(this.saveBatch).then((res) => {
        if (res.success) {
          console.log("存货分类与仓库关系-保存存货分类和仓库关系", res);
        }
      });
      //用友的接口
    },
    save_U8C() {
      //↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘注释↙↙↙↙↙↙↙↙↙↙↙↙↙↙↙↙
      //1、辅助计量问题已经解决
      //2、数目问题待解决
      //↗↗↗↗↗↗↗↗↗↗↗↗↗↗↗↗↗↗↗↗↖↖↖↖↖↖↖↖↖↖↖↖↖↖↖↖↖↖
      axios({
        headers: {
          "Access-Control-Allow-Origin": "*",
          trantype: "code",
          "Content-Type": "application/json",
          usercode: "13355262265",
          password: "5ef208ee90e5504a7b569ebbd6342634",
          system: "test",
        },
        method: "post",
        url: "/proxy/u8cloud/api/uapbd/invbasdoc/insert",
        data: {
          invbasdoc: [
            {
              parentvo: {
                // assistunit: true,
                pk_invcl: this.sort_U8C, //分类
                pk_taxitems: "4004", //税目、暂定先传默认值，让他在u8c上改
                invcode: this.xinzeng_formdata.inventoryNo, //存货编码
                invname: this.xinzeng_formdata.inventoryName, //存货名称
                pk_measdoc: "04", //主计量单位
              },
              childrenvo: [
                // pk_corp:"0001",//公司
                // mainmeasrate: 1,
                // pk_measdoc: "03", //单位
              ],
            },
          ],
        },
      }).then(function (response) {
        console.log(response);
      });
    },
    // getgongsi() {
    //   axios({
    //     headers: {
    //       "Access-Control-Allow-Origin": "*",
    //       trantype: "code",
    //       "Content-Type": "application/json",
    //       usercode: "13355262265",
    //       password: "5ef208ee90e5504a7b569ebbd6342634",
    //       system: "test",
    //     },
    //     method: "post",
    //     url: "/proxy/u8cloud/api/uapbd/bdcorp/query",
    //     data: {},
    //   }).then(function (response) {
    //     console.log(response);
    //     console.log(response.data);
    //   });
    // },

    // ==============分页======================
    handleTableChange(pagination) {
      this.pagination.current = pagination.current;
      this.pagination.pageSize = pagination.pageSize;
      this.queryParam.page = pagination.current;
      this.queryParam.size = pagination.pageSize;
      this.GetInventoryInformationList();
    },
    //删除
    onDelete(_id) {
      const deletePath = `?id=${_id}`;
      $http
        .DeleteInventoryInformation(deletePath)
        .then((res) => {
          if (res && res.code === 200) {
            this.$message.success("删除成功");
            this.GetInventoryInformationList();
          } else {
            this.$message.error("删除失败");
          }
        })
        .then(() => {
          this.data = [];
        });
    },
    //获取存货分类
    getInventoryClassificationList() {
      this.xinzeng_formdata.createTime = moment().format("YYYY-MM-DD");
      //获取存货分类
      common.GetSaveCargoClassification().then((res) => {
        // if (res.success) {
        // console.log("获取部门树", res);
        // let resetRes = res.result;
        // this.resetTree(resetRes);
        // this.inventoryNoList = resetRes;
        // console.log("this.depTree", this.depTree);
        // }
        // console.log(res, "存货分类");
        this.inventoryNoList = res.result;
        console.log("存货分类", res);
        // this.disableParent(this.inventoryNoList);
      });
    },
    //获取单位字典表
    getAuxiliaryUnit() {
      common.getAuxiliaryUnit().then((res) => {
        console.log("单位字典表", res);
        this.unitList = res.result;
      });
    },

    // 禁用父节点
    disableParent(Tree) {
      const setData = Tree.map((item) => {
        if (item.children && item.children.length) {
          item[`disabled`] = true;
          this.disableParent(item.children);
        }
        return item;
      });
      return setData;
    },

    // 选择仓库编码的change触发函数
    DepotNameChange(data) {
      console.log("data", data);
      let arr = data.split("|");
      console.log("这是存货名称", arr);
      this.formdata.inventoryId = arr[0];
      this.formdata.inventoryNo = arr[1];
      this.formdata.inventoryName = arr[2];
    },
    //↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘注释↙↙↙↙↙↙↙↙↙↙↙↙↙↙↙↙
    //存货分类
    sortchange(value, option) {
      console.log(`selected ${value}`);
      console.log(option, "11");
      // this.formdata.sort = value;

      //传分类value 获取对应分类下的存货信息接口
      $http.getInventoryTypeGoodsInfo("?sort=" + value).then((res) => {
        console.log(res, "1213123123213");
        if (res.success) {
          this.goodsList = res.result.list;
          this.$message.success("成功获取" + option + "存货信息");
        }
      });
    },
    onSelect() {
      console.log(...arguments);
    },
    //新增时，选择分类，自动获取存货编码
    sortchange_createInventoryNo(value, name, option) {
      console.log("选择的值", value);
      console.log("name", name);
      console.log("option", option);

      this.sort_U8C = option.triggerNode.$options.propsData.dataRef.number;
      console.log("this.sort_U8C", this.sort_U8C);

      $http.getcreateInventoryNo("?typeId=" + value).then((res) => {
        console.log(res);
        this.xinzeng_formdata.inventoryNo = res.message;
      });
      //自动获取所属仓库
      this.saveBatch_huixian = [];
      $http.getqueryBatchByTypeId("?typeId=" + value).then((res) => {
        if (res.success) {
          console.log("自动获取所属仓库", res);
          //遍历得到所属仓库的数组
          for (let i = 0; i < res.result.list.length; i++) {
            this.saveBatch_huixian.push(res.result.list[i].depotId);
          }
          console.log("this.saveBatch_huixian", this.saveBatch_huixian);

          this.ChangeWarehouse(this.saveBatch_huixian);

          //所属仓库回显
          this.xinzeng_formdata.inventoryInformationOrganizationId = this.$set(
            this.xinzeng_formdata,
            "inventoryInformationOrganizationId",
            this.saveBatch_huixian
          );
        }
      });
    },

    //↗↗↗↗↗↗↗↗↗↗↗↗↗↗↗↗↗↗↗↗↖↖↖↖↖↖↖↖↖↖↖↖↖↖↖↖↖↖

    //存货分类-搜索
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text
          .toLowerCase()
          .indexOf(input.toLowerCase()) >= 0
      );
    },
    exportExcel() {
      if (this.formdata.inventoryNo) {
        this.exportToExcel();
      } else {
        this.inventoryfiledataexportExcel();
      }
    },

    inventoryfiledataexportExcel() {
      this.showSpin = true; //打印加载中

      common.inventoryfiledataexportExcel().then((response) => {
        //如果后端返回的result是进过Blob处理的，直接 window.URL.createObjectURL(result)，如果没有，就需要先实例化new Blod处理之后再window.URL.createObjectURL(blob)。
        //文件名 文件保存对话框中的默认显示
        let fileName = "存货信息档案.xls";
        let data = response.data;
        if (!data) {
          return;
        }
        console.log(response);
        //构造a标签 通过a标签来下载
        let url = window.URL.createObjectURL(new Blob([data]));
        let a = document.createElement("a");
        a.style.display = "none";
        a.href = url;
        //此处的download是a标签的内容，固定写法，不是后台api接口
        a.setAttribute("download", fileName);
        document.body.appendChild(a);
        //点击下载
        a.click();
        // 下载完成移除元素
        document.body.removeChild(a);
        // 释放掉blob对象
        window.URL.revokeObjectURL(url);
      });
      this.showSpin = false; //打印加载中
    },
    exportToExcel() {
      this.showSpin = true; //打印加载中
      if (this.formdata.sort === undefined) {
        this.formdata.sort = "";
      }
      if (this.formdata.inventoryName === undefined) {
        this.formdata.inventoryName = "";
      }
      if (this.formdata.inventoryNo === undefined) {
        this.formdata.inventoryNo = "";
      }
      if (this.formdata.necessaryToCheck === undefined) {
        this.formdata.necessaryToCheck = "";
      }
      $http
        .GetInventoryInformationList(
          "?pageNo=1&pageSize=" +
            this.maxSize +
            "&invcode=" +
            this.formdata.inventoryNo +
            "&invname=" +
            this.formdata.inventoryName
        )
        .then((res) => {
          console.log("导入的数据", res.result.records);
          let array = res.result.records;
          this.exportBasic(array);
        });
    },

    // 接收数组，进行导出
    exportBasic(Array) {
      console.log("要导出的数据为:::::", Array);
      // 规整要导出的数据:::::
      let array = [];
      for (let i = 0; i < Array.length; i++) {
        let data = {
          序号: i + 1,
          存货编码: Array[i].invcode,
          存货名称: Array[i].invname,
          型号: Array[i].invtype,
          规格: Array[i].invspec,
          主计量单位: Array[i].pkMeasdoc_dictText,
          创建人: Array[i].creator,
          税目税率: Array[i].pkTaxitems,

          是否固定换算: Array[i].fixedflag,
          主计量单位换算系数: Array[i].mainmeasrate,
          辅计量: Array[i].pkConvert,
          封存标志: Array[i].sealflag,
          是否删除: Array[i].dr == "0" ? "否" : "是",
          是否应税劳务: Array[i].laborflag == "0" ? "否" : "是",
          是否允许负库存: Array[i].negallowed,
        };
        array.push(data);
      }
      // 生成 sheet 表格 数据
      let sheet = XLSX.utils.json_to_sheet(array, {
        // 对导出内容进行相应的排序,手动排序。
        header: [
          "序号",
          "存货编码",
          "存货名称",
          "型号",
          "规格",
          "主计量单位",
          "创建人",
          "税目税率",
          "是否固定换算",
          "主计量单位换算系数",
          "辅计量",
          "封存标志",
          "是否删除",
          "是否应税劳务",
          "是否允许负库存",
        ],
      });
      // 生成导出表格
      let blob = sheet2blob(sheet);
      try {
        FileSaver.saveAs(
          new Blob([blob], {
            type: "application/octet-stream",
          }),
          "存货信息档案.xlsx" // 导出文件夹名称
        );
      } catch (e) {
        console.log(e);
      }
      this.showSpin = false; //打印加载中
    },

    //同步用友数据
    /*   SyncData() {
      this.asyncLoad = true; //

      common.asyncInventoryInfoFile().then((res) => {
        console.log("同步用友的数据", res);
        if (res.code == 200) {
          this.$message.success("同步成功");
        } else {
          this.$message.error("同步失败");
        }
        this.asyncLoad = false;
      });
      this.GetInventoryInformationList();
    }, */
    SyncData() {
      this.Loading = true;
      let data = "?transFileName=" + "SyncInventoryFileDatabaseFields.ktr";
      common.asyncInventoryInfoFile(data).then((res) => {
        console.log("res", res);
        if (res.success) {
          this.$message.success("同步成功！");
          this.GetInventoryInformationList();
          this.Loading = false;
        } else {
          this.$message.error("同步失败！" + res.message);
          this.Loading = false;
        }
      });
    },
  },
};
</script>

<style scoped>
</style>
